// GlobalCbtHook.cpp
//   by Chris Wilson

#include "stdafx.h"
#include <windows.h>
#include "GlobalCbtHook.h"

HHOOK hookCbt = NULL;
 
//
// Store the application instance of this module to pass to
// hook initialization. This is set in DLLMain().
//
HINSTANCE g_appInstance = NULL;


static LRESULT CALLBACK CbtHookCallback(int code, WPARAM wparam, LPARAM lparam);
 
bool InitializeCbtHook(int threadID, HWND destination)
{
	if (g_appInstance == NULL)
	{
		return false;
	}
 
	hookCbt = SetWindowsHookEx(WH_CBT, (HOOKPROC)CbtHookCallback, g_appInstance, threadID);
	return hookCbt != NULL;
}

void UninitializeCbtHook()
{
	if (hookCbt != NULL)
		UnhookWindowsHookEx(hookCbt);
	hookCbt = NULL;
}

static LRESULT CALLBACK CbtHookCallback(int code, WPARAM wparam, LPARAM lparam)
{
	if (code >= 0)
	{
		UINT msg = 0;

		if (code == HCBT_ACTIVATE)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_ACTIVATE");
		else if (code == HCBT_CREATEWND)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_CREATEWND");
		else if (code == HCBT_DESTROYWND)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_DESTROYWND");
		else if (code == HCBT_MINMAX)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_MINMAX");
		else if (code == HCBT_MOVESIZE)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_MOVESIZE");
		else if (code == HCBT_SETFOCUS)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_SETFOCUS");
		else if (code == HCBT_SYSCOMMAND)
			msg = RegisterWindowMessage(L"WILSON_HOOK_HCBT_SYSCOMMAND");

		HWND dstWnd = (HWND)GetProp(GetDesktopWindow(), L"WILSON_HOOK_HWND_CBT");

		if (msg != 0)
			SendNotifyMessage(dstWnd, msg, wparam, lparam);
	}

	return CallNextHookEx(hookCbt, code, wparam, lparam);
}
 